import { Sensor } from 'store';
import { sendData } from 'socketApi';

type Props = {
  sensor: Sensor;
};

const CustomQueries = ({ sensor }: Props) => {
  const is2Disabled = sensor.channel2.sequenceNumber === null;
  const is3Disabled = sensor.channel3.sequenceNumber === null;

  const uint8TSeq = (seq: number) => {
    const m = seq >> 8;
    const l = seq - (m << 8);

    return [m, l];
  };

  const snQuery = (ch: number) => () => {
    if ((ch === 2) && (sensor.channel2.sequenceNumber !== null)) {
      sendData([ch, 0, ...uint8TSeq(sensor.channel2.sequenceNumber)]);
    }

    if ((ch === 3) && (sensor.channel3.sequenceNumber !== null)) {
      sendData([ch, 0, ...uint8TSeq(sensor.channel3.sequenceNumber)]);
    }
  };

  const dataQuery = (ch: number) => () => {
    if ((ch === 2) && (sensor.channel2.sequenceNumber !== null)) {
      sendData([ch, 0x20, ...uint8TSeq(sensor.channel2.sequenceNumber)]);
    }

    if ((ch === 3) && (sensor.channel3.sequenceNumber !== null)) {
      sendData([ch, 0x20, ...uint8TSeq(sensor.channel3.sequenceNumber)]);
    }
  };

  return (
    <>
      <button
        onClick={snQuery(2)}
        disabled={is2Disabled}
        className="btn btn-xs btn-primary"
      >
        Sn2
      </button>

      <button
        onClick={snQuery(3)}
        disabled={is3Disabled}
        className="btn btn-xs btn-secondary"
      >
        Sn3
      </button>

      <button
        onClick={dataQuery(2)}
        disabled={is2Disabled}
        className="btn btn-xs btn-primary"
      >
        D2
      </button>

      <button
        onClick={dataQuery(3)}
        disabled={is3Disabled}
        className="btn btn-xs btn-secondary"
      >
        D3
      </button>
    </>
  );
};

export default CustomQueries;
